﻿define(function (require, exports, module) {

    // define the name of the UI component
    var ui_name = "memberbox"

    // initialize object
    var memberbox = $.memberbox = {

        // default values

        def: {
            userData: null, //默認數據
            groupData: null,
            width: "100%",
            addItem: false,
            removeItem: false,
            clickItem: function () { },
            completeOp: {}
        },
        setDefaults: function (defaultOptions) {
            this.defaults = $.extend({}, this.def, defaultOptions);
        }
    };

    $.fn.memberbox = function (options) {

        // method calling
        if (typeof options == 'string') {
            var args = Array.prototype.slice.call(arguments, 1),
			res;
            this.each(function () {
                var data = $.data(this, ui_name);
                if (data) {
                    var meth = data[options];
                    if (meth) {
                        var r = meth.apply(this, args);
                        if (res === undefined) {
                            res = r;
                        }
                    }
                }
            });
            if (res !== undefined) {
                return res;
            }
            return this;
        }

        // initialize options
        options = $.extend({}, memberbox.def, options);

        var temp = '<span class="ez-usbox-item ${class}">' +
                        '<a>' +
                            '<span>${text}</span>' +
                            '<input type="hidden" value="${value}"/>' +
                        '</a>' +
                    '</span>';

        var _idList = "";
        var _list = [];

        this.each(function () {
            var _self = this;

            //initialize
            initUsBox();


            // initialize callback
            for (var key in options) {
                var value = options[key];
                if (typeof value == 'function') {
                    // bind callbacks
                    $(_self).bind(key, value);
                }
            }



            function initUsBox() {
                //dom
                var inc = $('<span class="ez-usbox-boxc"/>');
                var input = $('<input type="text" class="ez-usbox-input"/>').appendTo(inc);
                $(_self).addClass("ez-usbox").width(options.width).append(inc);

                $(_self).click(function () {
                    $(input).focus();
                })

                $(input).keydown(function (e) {
                    if ($(this).val() == "" && e.keyCode == 8) {
                        if (_list.length > 0) {
                            var lastData = _list.pop();
                            removeitem(lastData, $('.ez-usbox-item:last'));
                            
                        }
                    }

                })

            }


            function unique(arry) {
                var a = {}; for (var i = 0; i < arry.length; i++) {
                    if (typeof a[arry[i]] == "undefined")
                        a[arry[i]] = 1;
                }
                arry.length = 0;
                for (var i in a)
                    arry[arry.length] = i;
                return arry;
            };

            function additem(data) {
                _list.push(data);

                var ezclass = (data.Tag == "user" ? "ez-user" : "ez-group");
                var $item = $(temp.replace("${text}", data.Name)
                                  .replace("${value}", data.Id)
                                  .replace("${class}", ezclass));

                var isHolding = false;

                //for mobile 
                $item.taphold(function (e) {
                    $item.css({ 'border': 'solid 1px #FF4040' });
                    setTimeout(function () {
                        removeitem(data, $item);
                    }, 500)
                });

                //for pc
                $item.mousedown(function (e) {
                    isHolding = true;

                    $item.css({ 'border': 'solid 1px #FF4040' });
                    setTimeout(function () {
                        if (isHolding)
                            removeitem(data, $item);
                    }, 1000)

                }).mouseup(function (e) {
                    isHolding = false;

                    $item.css({ 'border': 'solid 1px #AAA' });
                });

                $('.ez-usbox-boxc').before($item);

                var ids = _idList != "" ? _idList.split(",") : []

                ids.push(data.Id);
                _idList = ids.join(",");
            }

            function removeitem(data, dom) {
                $(dom).remove();

                //todo:重搆双重循环
                var ids = _idList.split(",");
                var idIngroup = data.Id.split(",");

                for (var key in idIngroup) {
                    var index = -1;
                    for (var i = ids.length - 1; i >= 0; i--) {
                        if (idIngroup[key] == ids[i]) {
                            index = i;
                            break;
                        }
                    }
                    if (index > -1) {
                        ids.splice(index, 1);
                    }
                }


                _idList = ids.join(",");
            }


            function removeAll() {
                $('.ez-user').remove();
                $('.ez-group').remove();
            }

            var publicMethods = {
                getIdList: function () {
                    var idList = "";
                    if (_idList.indexOf('everyone') != -1)
                        idList = 'everyone';
                    else {
                        var ids = unique(_idList.split(','));
                        idList = ids.join(',');
                    }

                    return idList;
                },
                addUsers: function (users) {
                    for (var key in users) {
                        var newUser = {
                            Name: users[key].Name,
                            Id: users[key].Id,
                            Tag: "user"
                        }
                        additem(newUser);
                    }
                },
                addGroups: function (groups) {
                    for (var key in groups) {
                        var newgroup = {
                            Name: groups[key].Description,
                            Id: groups[key].Memberstring,
                            Tag: "group"
                        }
                        additem(newgroup);
                    }
                },
                removeAll: function () {
                    _idList = "";
                    removeAll();
                }
            };

            $.data(this, ui_name, publicMethods);
        });

        return this;
    };



})




